/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.wechat.web;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.car.entity.GpsCarInfo;
import com.thinkgem.jeesite.modules.car.entity.GpsCompany;
import com.thinkgem.jeesite.modules.car.entity.GpsInfo;
import com.thinkgem.jeesite.modules.car.entity.GpsMember;
import com.thinkgem.jeesite.modules.car.service.GpsCarInfoService;
import com.thinkgem.jeesite.modules.car.service.GpsCompanyService;
import com.thinkgem.jeesite.modules.car.service.GpsInfoService;
import com.thinkgem.jeesite.modules.car.service.GpsMemberService;
import com.thinkgem.jeesite.modules.wechat.utils.OauthUtils;
import com.thinkgem.jeesite.modules.wechat.utils.TokenUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 车辆信息Controller
 * @author xiaoqian
 * @version 2018-01-06
 */
@Controller
@RequestMapping(value = "${frontPath}/wechat/oauth")
public class OauthFrontController extends BaseController {

	private static Logger logger = LoggerFactory.getLogger(OauthFrontController.class);

	@Autowired
	private GpsMemberService gpsMemberService;

	/**
	 * 公司列表
	 * @return
	 */
	@RequestMapping(value = "")
	public String oauth(String code,String state) {
		Map<String,Object> token = OauthUtils.getSnsToken(code);
		if(token != null){
			Map<String,Object> userinfo = OauthUtils.getSnsUserinfo(token.get("access_token")+"",token.get("openid")+"");
			if(userinfo != null){
				GpsMember gpsMember = new GpsMember();
				gpsMember.setOpenid(userinfo.get("openid")+"");
				gpsMember = gpsMemberService.getGpsMemberByOpenId(gpsMember);
				if(gpsMember == null){
					gpsMember = new GpsMember(userinfo);
					gpsMemberService.save(gpsMember);
				}
			}
		}else{
			logger.error("code:"+code +"   通过code获取失败");
		}
		return "redirect:" + Global.getFrontPath() + "/gps/companyList";
	}



}